﻿using CrankShaftAnalysisSystem.Devices;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CrankShaftAnalysisSystem
{
    public partial class FormIK220 : Form
    {
        EncoderERM2400 encoder;
        LinearLC485 linear;
        public FormIK220()
        {
            InitializeComponent();
            encoder = EncoderERM2400.Instance;
            linear = LinearLC485.Instance;
        }

        private void FormIK220_FormClosing(object sender, FormClosingEventArgs e)
        {
            Hide();
            e.Cancel = true;
        }

        private void FormIK220_Load(object sender, EventArgs e)
        {
            
        }

        private void tmUI_Tick(object sender, EventArgs e)
        {
            if(encoder.Device.Initialised)
            {
                double ang = encoder.Device.ReadAngleRadians(out _);
                ang = ang / Math.PI * 180.0;
                lbCH0.Text = ang.ToString("F4")+"Degrees";
            }
            if(linear.Initialised)
            {
                var height = linear.ReadLinearDis();
                lbCH1.Text = height.ToString("F2")+"um";
            }
            ledRefFound.On = encoder.Device.RefFound;
            ledWarning.On = linear.Warning;
            lbMultiTurn.Text = encoder.Device.MultiTurn.ToString();
            lbAbsoluteDegree.Text = encoder.Device.TotalDegrees.ToString("F4");
            lbMultiturnOffset.Text = encoder.Device.MultiTurnOffset.ToString();
            lbMultiturnShadow.Text = encoder.Device.MultiTurnShadow.ToString();
        }

        private void btnInit_Click(object sender, EventArgs e)
        {
            tmUI.Start();
        }

        private void btnRestart_Click(object sender, EventArgs e)
        {
            DialogResult ret = MessageBox.Show("角度编码器将会重置，需要重新找零点", "WARNING", MessageBoxButtons.OKCancel);
            if (ret == DialogResult.Cancel)
                return;
            encoder.Device.Init();
            encoder.Device.Begin();
            linear.Begin();
            tmUI.Start();
        }

        private void btnClearMultiTurn_Click(object sender, EventArgs e)
        {
            encoder.Device.ClearMultiTurn();
        }
    }
}
